#include "fix_checksum.h"

extern FILE *ROM;
extern long rom_pos;

//-----my subroutines-----
unsigned short CalcCheckSum()
{
     /* Declare vars. for reading */
     unsigned int calsum = 0;
     unsigned int curnum = 0;
     long rom_len=lof();
     long buf_pos = 0x200;
     unsigned char *fileBuffer = (unsigned char*)malloc(rom_len);
     
     /* Faster to read full rom into a buffer */
     rom_pos = 0;
     fseek(ROM, rom_pos, 0);
     fread(fileBuffer, rom_len, 1, ROM);

     /* calculate checksum */
     while (buf_pos < rom_len)
     {
         curnum = ((fileBuffer[buf_pos] << 8) + (fileBuffer[buf_pos + 1]));
         calsum = calsum + curnum;
         buf_pos = buf_pos + 2;
     }   //end while
     
     /* free memory */
     free(fileBuffer);
     
     /* return calculated checksum */
     return (unsigned short)LOWORD(calsum);
}    //end of func.

unsigned short GetRomSum()
{
     //Variable for sum stored in rom
     short romsum = 0;
     
     //Navigate to checksum position
     rom_pos = 0x18E;
     fseek(ROM, rom_pos, 0);
     
     //Read checksum
     fread(&romsum, 2, 1, ROM);
     romsum = jntohs(romsum);
     
     return romsum;
}    //end of func.

void FixRomSum(unsigned short fixVal)
{
     //Navigate to checksum position
     short nfVal = fixVal;
     rom_pos = 0x18E;
     fseek(ROM, rom_pos, 0);
     
     //Read checksum
     nfVal = jhtons(nfVal); 
     fwrite(&nfVal, 2, 1, ROM);
}    //end of func.


